package com.itheima.ydd.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.ydd.common.*;
import com.itheima.ydd.dto.YddArticleDto;
import com.itheima.ydd.entity.YddArticle;
import com.itheima.ydd.entity.YddCate;
import com.itheima.ydd.service.IYddArticleService;
import com.itheima.ydd.service.IYddCateService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author author
 * @since 2022-05-22
 */
@RestController
@RequestMapping("/ydd_article")
public class YddArticleController {

    @Autowired
    private IYddArticleService yddArticleService;

    @Autowired
    private IYddCateService yddCateService;

    /**
     * 分页条件查询
     *
     * @param startTime
     * @param endTime
     * @param title
     * @param cateid
     * @param page
     * @param limit
     * @return
     */
    //分页条件查询
    @GetMapping("/list")
    public R page(@RequestParam(value = "start_time",required = false)Long startTime,
                           @RequestParam(value = "end_time",required = false)Long endTime,
                           @RequestParam(value = "title",required = false)String title,
                           @RequestParam(value = "cateid",required = false)Integer cateid,
                           @RequestParam("page")int page,
                           @RequestParam("limit")int limit){

        //创建分页查询对象
        Page<YddArticle> pageInfo = new Page<>(page,limit);

        //创建条件查询
        LambdaQueryWrapper<YddArticle> queryWrapper = new LambdaQueryWrapper<>();
            //根据日期时间查询
        queryWrapper.ge(startTime != null,YddArticle::getCreateDate, startTime)
                    .le(endTime != null,YddArticle::getCreateDate,endTime);
            //根据标题查询
        queryWrapper.like(YddArticle::getTitle,title);
            //根据分类查询
        queryWrapper.eq(cateid != null,YddArticle::getCateid,cateid);

        //获取查询集合
        yddArticleService.page(pageInfo, queryWrapper);
        List<YddArticle> records = pageInfo.getRecords();

        Page<YddArticleDto> dtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,dtoPage,"record");

        List<YddArticleDto> articleDtos = records.stream().map(item -> {
            YddArticleDto yddArticleDto = new YddArticleDto();
            BeanUtils.copyProperties(item,yddArticleDto);
            LambdaQueryWrapper<YddCate> cateLambdaQueryWrapper = new LambdaQueryWrapper<>();
            cateLambdaQueryWrapper.eq(YddCate::getId,item.getCateid());
            YddCate yddCate = yddCateService.getOne(cateLambdaQueryWrapper);
            if (yddCate != null) {
                yddArticleDto.setCatename(yddCate.getCatename());
            }
            return yddArticleDto;
        }).collect(Collectors.toList());

        R r=new R();
        r.putData("count",Integer.parseInt(String.valueOf(pageInfo.getTotal())));
        r.putData("totalPages",(int)Math.ceil((Double.valueOf(String.valueOf(pageInfo.getTotal()))/pageInfo.getSize())));
        r.putData("pageSize",Integer.parseInt(String.valueOf(pageInfo.getSize())));
        r.putData("currentPage",Integer.parseInt(String.valueOf(pageInfo.getCurrent())));
        r.putData("data",articleDtos);

        r.setErrmsg("");
        r.setErrno(0);
        return r;
    }

    /**
     * 新增文章
     *
     * @param yddArticle
     * @return
     */
    @PostMapping("/add")
    public R save(@RequestBody YddArticle yddArticle){
        yddArticle.setUpdateDate(yddArticle.getUpdateDate());
        yddArticle.setPic("/" + yddArticle.getPic());
        yddArticleService.save(yddArticle);
        return R.success("success",yddArticle);

    }

    /**
     * 文章删除
     *
     * @param id
     * @return
     */
    @GetMapping("/del/{id}")
    public R delete(@PathVariable Integer id){
        YddArticle yddArticle = yddArticleService.getById(id);
        if ("1".equals(yddArticle.getDefaultData())){
            return R.error("默认数据,无法删除");
        }
        yddArticleService.removeById(id);
        return R.success("success","");
    }

    /**
     * 修改
     *
     * @return
     */
    @PostMapping("/update")
    public ResultData update(@RequestBody YddArticle yddArticle){

        //修改时间
        yddArticle.setUpdateDate(System.currentTimeMillis());
        yddArticle.setPic("/" + yddArticle.getPic());
        yddArticleService.updateById(yddArticle);
        return ResultData.ok("success",yddArticle) ;
    }

    /**
     * 文章详情
     *
     * @param id
     * @return
     */
    @GetMapping("/rowInfo")
    public ResultData rowInfo(String id){

        try {
            YddArticle yddArticle = yddArticleService.getById(Integer.parseInt(id));
            return ResultData.ok("success",yddArticle);
        } catch (NumberFormatException e) {
            throw new BusinessException("未选择修改数据   ");
        }

    }

}
